package com.konsung.ksdc.common.network;

import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONObject;

import okhttp3.Response;

/**
 * 请求回调
 */
public abstract class RequestCallback extends Callback<ResponseBean> {
    public static final String RESULT_CODE = "resultCode";
    public static final String ENTITY = "entity";
    public static final String LIST = "list";

    @Override
    public ResponseBean parseNetworkResponse(Response response) throws Exception {

        String responsedJsonString = response.body().string();
        return parseReponseStringToBean(responsedJsonString);
    }

    /**
     * 提取JSON中三个节点到实体对象
     * 三个节点分别为：resultCode, entity, list
     * @param jsonString json数据
     * @return 解析数据
     * @throws Exception 异常
     */
    private ResponseBean parseReponseStringToBean(String jsonString) throws Exception {

        // 将JSON字符串转成原生JSON对象
        JSONObject jsonObject = new JSONObject(jsonString);
        String resultCode = jsonObject.getString(RESULT_CODE);
        Object entity = jsonObject.get(ENTITY);
        Object list = jsonObject.get(LIST);

        ResponseBean bean = new ResponseBean();
        bean.setResultCode(resultCode);
        bean.setEntity(entity == null ? "" : entity.toString());
        bean.setList(list == null ? "" : list.toString());

        return bean;
    }
}